//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.authine.cloudpivot.engine.service.impl.bizform;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.authine.cloudpivot.engine.api.exceptions.ServiceException;
import com.authine.cloudpivot.engine.api.model.bizform.BizFormModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectModel;
import com.authine.cloudpivot.engine.api.utils.ModelUtil;
import com.authine.cloudpivot.engine.component.cache2.api.CacheConfig;
import com.authine.cloudpivot.engine.component.query.api.FilterExpression;
import com.authine.cloudpivot.engine.component.query.api.FilterExpression.Op;
import com.authine.cloudpivot.engine.component.query.api.helper.Q;
import com.authine.cloudpivot.engine.domain.bizform.BizForm;
import com.authine.cloudpivot.engine.domain.bizmodel.BizDataRule;
import com.authine.cloudpivot.engine.domain.bizmodel.BizProperty;
import com.authine.cloudpivot.engine.domain.bizmodel.BizSchema;
import com.authine.cloudpivot.engine.enums.ErrCode;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.engine.enums.type.BizFormType;
import com.authine.cloudpivot.engine.enums.type.BizPropertyType;
import com.authine.cloudpivot.engine.enums.type.bizmodel.DataRuleType;
import com.authine.cloudpivot.engine.repository.bizform.BizFormRepository;
import com.authine.cloudpivot.engine.service.bizform.BizFormJsonResolveService;
import com.authine.cloudpivot.engine.service.bizform.BizFormService;
import com.authine.cloudpivot.engine.service.bizmodel.BizDataRuleService;
import com.authine.cloudpivot.engine.service.bizmodel.BizPropertyService;
import com.authine.cloudpivot.engine.service.bizmodel.BizSchemaService;
import com.authine.cloudpivot.engine.service.bizquery.BizQueryService;
import com.authine.cloudpivot.engine.service.impl.ListCacheSupportedServiceImpl;
import com.authine.cloudpivot.foundation.orm.api.Db;
import com.authine.cloudpivot.foundation.orm.api.dml.BizObjectRepository;
import com.authine.cloudpivot.foundation.orm.api.model.BizObjectQueryObject;
import com.authine.cloudpivot.foundation.util.api.ValidateUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

@Service
@Transactional
public class BizFormServiceImpl extends ListCacheSupportedServiceImpl<BizForm, String> implements BizFormService {
    private static final Logger log = LoggerFactory.getLogger(BizFormServiceImpl.class);
    private static final int GROUP = 200;
    private static final int DESCRIPTION = 202;
    private static final int TITLE = 203;
    private static final int WORK_SHEET = 80;
    private static final int REVERSE_WORK_SHEET = 90;
    private static final int MULT_WORK_SHEET = 81;
    private static final int CUSTOM_HTML = 400;
    private static final int TABS = 500;
    private static final String SINGLE_TXT_TYPE = "1";
    private static final String SUBLIST_TYPE = "201";
    private static final int NO_REPEAT_ERROR_CODE = 800150006;
    @Autowired
    private BizFormRepository bizFormRepository;
    @Autowired
    private BizPropertyService bizPropertyService;
    @Autowired
    private BizSchemaService bizSchemaService;
    @Autowired
    private BizQueryService bizQueryService;
    @Autowired
    private BizObjectRepository bizObjectRepository;
    @Autowired
    private BizDataRuleService bizDataRuleService;
    @Autowired
    private BizFormJsonResolveService bizFormJsonResolveService;
    @Autowired
    private Db db;

    public BizFormServiceImpl() {
    }

    private static boolean compareRepeat(List<String> list) {
        Set<String> set = new HashSet(list);
        return list.size() != set.size();
    }

    public JpaRepository getRepository() {
        return this.bizFormRepository;
    }

    protected BizForm loadFromDBByBizKey(String bizKey) {
        String[] params = BizForm.decodeBizKey(bizKey);
        if (params != null && params.length == 2) {
            List<BizForm> list = this.bizFormRepository.findBySchemaCodeAndCode(params[0], params[1]);
            return CollectionUtils.isNotEmpty(list) ? (BizForm)list.get(0) : null;
        } else {
            return null;
        }
    }

    public List<BizForm> getListBySchemaCode(String schemaCode) {
        return this.loadCachedList(schemaCode, (perm) -> {
            return this.bizFormRepository.findBySchemaCodeAndFormTypeIsNotOrderBySortKey(schemaCode, BizFormType.PRINT_TEMPLATE);
        });
    }

    public List<BizForm> getAllListBySchemaCode(String schemaCode) {
        return this.loadCachedList(schemaCode + "All", (perm) -> {
            return this.bizFormRepository.findBySchemaCode(schemaCode);
        });
    }

    public List<BizForm> getListByAppCode(String appCode) {
        List<BizForm> bizForms = Lists.newArrayList();
        List<BizSchema> bizSchemas = this.bizSchemaService.findBizSchemaByAppCode(appCode);
        Iterator var4 = bizSchemas.iterator();

        while(var4.hasNext()) {
            BizSchema bizSchema = (BizSchema)var4.next();
            List<BizForm> listBySchemaCode = this.bizFormRepository.findBySchemaCode(bizSchema.getCode());
            bizForms.addAll(listBySchemaCode);
        }

        bizForms.remove((Object)null);
        return bizForms;
    }

    public BizForm getBySchemaCodeAndFormCode(String schemaCode, String formCode) {
        if (!StringUtils.isEmpty(schemaCode) && !StringUtils.isEmpty(formCode)) {
            return (BizForm)this.getByBizKey(BizForm.encodeBizKey(new String[]{schemaCode, formCode}));
        } else {
            List<BizForm> list = this.bizFormRepository.findBySchemaCodeAndCode(schemaCode, formCode);
            return CollectionUtils.isNotEmpty(list) ? (BizForm)list.get(0) : null;
        }
    }

    public BizForm getByShortCode(String shortCode) {
        List<BizForm> list = this.bizFormRepository.findByShortCode(shortCode);
        return CollectionUtils.isNotEmpty(list) ? (BizForm)list.get(0) : null;
    }

    public Boolean delete(String schemaCode, String formCode) {
        boolean isDelete = false;
        BizForm entity = this.getBySchemaCodeAndFormCode(schemaCode, formCode);
        if (null != entity) {
            this.delete(entity);
            isDelete = true;
        }

        return isDelete;
    }

    public Boolean publish(BizForm form) {
        boolean isPublish = false;
        Set<String> deleteList = new HashSet();
        String draftJson = form.getDraftAttributesJson();
        log.debug("草稿的控件属性:{}", draftJson);
        this.validateProperty(draftJson, form.getSchemaCode(), deleteList);
        if (CollectionUtils.isNotEmpty(deleteList)) {
            log.debug("被删除的数据项对象:{}", deleteList);
            throw new ServiceException(ErrCode.BIZ_PROPERTY_NOT_EXIST, deleteList);
        } else {
            BizForm entity = (BizForm)this.get(form.getId());
            if (null == entity) {
                throw new ServiceException(ErrCode.BIZ_SHEET_NOT_EXIST);
            } else {
                entity.setModifiedBy(form.getModifiedBy());
                entity.setName(form.getName());
                entity.setName_i18n(form.getName_i18n());
                entity.setPublished(true);
                entity.setPublishedViewJson(form.getDraftViewJson());
                entity.setPublishedAttributesJson(form.getDraftAttributesJson());
                entity.setDraftViewJson(form.getDraftViewJson());
                entity.setDraftAttributesJson(form.getDraftAttributesJson());
                entity.setExternalLinkAble(form.getExternalLinkAble());
                entity.setShortCode(form.getShortCode());
                entity.setDraftActionsJson(form.getDraftActionsJson());
                entity.setDraftHtmlJson(form.getDraftHtmlJson());
                entity.setPublishedHtmlJson(form.getPublishedHtmlJson());
                entity.setPublishedActionsJson(form.getPublishedActionsJson());
                entity.setPrintTemplateJson(form.getPrintTemplateJson());
                entity.setQrCodeAble(form.getQrCodeAble());
                entity.setPdfAble(form.getPdfAble());
                entity.setTempAuthSchemaCodes(form.getTempAuthSchemaCodes());
                entity.setBorderMode(form.getBorderMode());
                entity.setLayoutType(form.getLayoutType());
                entity.setFormComment(form.getFormComment());
                entity.setPrintJson(form.getPrintJson());
                entity.setFormTrack(form.getFormTrack());
                entity.setTrackDataCodes(form.getTrackDataCodes());
                entity.setFormSystemVersion(form.getFormSystemVersion());
                entity.setDraftSchemaOptionsJson(form.getDraftSchemaOptionsJson());
                entity.setExistDraft(form.getExistDraft());
                this.update(entity);
                isPublish = this.bizSchemaService.checkSummaryAndPublish(entity.getSchemaCode(), form.getCreatedBy());
                return isPublish;
            }
        }
    }

    public BizForm save(BizForm bizForm) {
        return this.save(bizForm, true);
    }

    public BizForm save(BizForm bizForm, boolean genPrintSheetFlag) {
        if (StringUtils.isBlank(bizForm.getName())) {
            log.debug(ErrCode.BIZ_SHEET_NAME_EMPTY.getErrMsg());
            throw new ServiceException(ErrCode.BIZ_SHEET_NAME_EMPTY);
        } else if (bizForm.getName().trim().length() > 50) {
            log.debug(ErrCode.BIZ_SHEET_NAME_LIMIT.getErrMsg());
            throw new ServiceException(ErrCode.BIZ_SHEET_NAME_LIMIT);
        } else if (StringUtils.isBlank(bizForm.getSchemaCode())) {
            log.debug(ErrCode.BIZ_SCHEMA_CODE_EMPTY.getErrMsg());
            throw new ServiceException(ErrCode.BIZ_SCHEMA_CODE_EMPTY);
        } else if (StringUtils.isBlank(bizForm.getCode())) {
            log.debug(ErrCode.BIZ_SHEET_CODE_EMPTY.getErrMsg());
            throw new ServiceException(ErrCode.BIZ_SHEET_CODE_EMPTY);
        } else if (!ValidateUtils.validCode(bizForm.getCode())) {
            log.debug("表单项编码无效：{}", bizForm.getCode());
            throw new ServiceException(ErrCode.BIZ_SHEET_CODE_INVALID);
        } else {
            BizForm entity = this.getBySchemaCodeAndFormCode(bizForm.getSchemaCode(), bizForm.getCode());
            if (null != entity) {
                log.debug(ErrCode.BIZ_SHEET_EXIST.getErrMsg());
                throw new ServiceException(ErrCode.BIZ_SHEET_EXIST);
            } else {
                Integer maxSortKey = this.bizFormRepository.findSortKeyBySchemaCode(bizForm.getSchemaCode());
                bizForm.setSortKey(maxSortKey == null ? 1 : maxSortKey + 1);
                if (BizFormType.CUSTOMIZE_SHEET.equals(bizForm.getFormType())) {
                    BizForm form = (BizForm)super.save(bizForm);
                    if (form.getPublished()) {
                        this.bizSchemaService.checkSummaryAndPublish(bizForm.getSchemaCode(), bizForm.getCreatedBy());
                    }

                    return form;
                } else if (BizFormType.PRINT_TEMPLATE.equals(bizForm.getFormType())) {
                    return (BizForm)super.save(bizForm);
                } else {
                    if (bizForm.getPublished() == null || !bizForm.getPublished()) {
                        bizForm.setPublished(false);
                    }

                    Map<String, String> map = new HashMap();
                    map.put("sheetCode", bizForm.getCode().concat("_print"));
                    map.put("name", bizForm.getName());
                    map.put("name_i18n", bizForm.getName_i18n());
                    List<Map<String, String>> listMap = new ArrayList();
                    listMap.add(map);
                    bizForm.setPrintTemplateJson(JSON.toJSONString(listMap));
                    if (genPrintSheetFlag) {
                        BizForm bizSheetPrint = new BizForm();
                        bizSheetPrint.setName(bizForm.getName());
                        bizSheetPrint.setName_i18n(bizForm.getName_i18n());
                        bizSheetPrint.setCode(bizForm.getCode().concat("_print"));
                        bizSheetPrint.setFormType(BizFormType.PRINT_TEMPLATE);
                        bizSheetPrint.setSchemaCode(bizForm.getSchemaCode());
                        bizSheetPrint.setPdfAble("true");
                        bizSheetPrint.setPrintJson(bizForm.getPrintJson());
                        super.save(bizSheetPrint);
                    }

                    return (BizForm)super.save(bizForm);
                }
            }
        }
    }

    public BizForm importSave(BizForm bizForm) {
        if (StringUtils.isBlank(bizForm.getName())) {
            log.debug(ErrCode.BIZ_SHEET_NAME_EMPTY.getErrMsg());
            throw new ServiceException(ErrCode.BIZ_SHEET_NAME_EMPTY);
        } else if (bizForm.getName().trim().length() > 50) {
            log.debug(ErrCode.BIZ_SHEET_NAME_LIMIT.getErrMsg());
            throw new ServiceException(ErrCode.BIZ_SHEET_NAME_LIMIT);
        } else if (StringUtils.isBlank(bizForm.getSchemaCode())) {
            log.debug(ErrCode.BIZ_SCHEMA_CODE_EMPTY.getErrMsg());
            throw new ServiceException(ErrCode.BIZ_SCHEMA_CODE_EMPTY);
        } else if (StringUtils.isBlank(bizForm.getCode())) {
            log.debug(ErrCode.BIZ_SHEET_CODE_EMPTY.getErrMsg());
            throw new ServiceException(ErrCode.BIZ_SHEET_CODE_EMPTY);
        } else if (!ValidateUtils.validCode(bizForm.getCode())) {
            log.debug("表单项编码无效：{}", bizForm.getCode());
            throw new ServiceException(ErrCode.BIZ_SHEET_CODE_INVALID);
        } else {
            Integer maxSortKey = this.bizFormRepository.findSortKeyBySchemaCode(bizForm.getSchemaCode());
            bizForm.setSortKey(maxSortKey == null ? 1 : maxSortKey + 1);
            if (BizFormType.CUSTOMIZE_SHEET.equals(bizForm.getFormType())) {
                BizForm form = (BizForm)super.save(bizForm);
                if (form.getPublished()) {
                    this.bizSchemaService.checkSummaryAndPublish(bizForm.getSchemaCode(), bizForm.getCreatedBy());
                }

                return form;
            } else {
                if (bizForm.getPublished() == null || !bizForm.getPublished()) {
                    bizForm.setPublished(false);
                }

                Map<String, String> map = new HashMap();
                map.put("sheetCode", bizForm.getCode().concat("_print"));
                map.put("name", bizForm.getName());
                map.put("name_i18n", bizForm.getName_i18n());
                List<Map<String, String>> listMap = new ArrayList();
                listMap.add(map);
                bizForm.setPrintTemplateJson(JSON.toJSONString(listMap));
                return (BizForm)super.save(bizForm);
            }
        }
    }

    public BizForm update(BizForm form) {
        if (null == form) {
            return null;
        } else {
            BizForm entity = (BizForm)this.get(form.getId());
            if (null == entity) {
                log.debug(ErrCode.BIZ_SHEET_NOT_EXIST.getErrMsg());
                throw new ServiceException(ErrCode.BIZ_SHEET_NOT_EXIST);
            } else {
                String draftJson = form.getDraftAttributesJson();
                if (BizFormType.CUSTOMIZE_SHEET.equals(form.getFormType())) {
                    if (!form.getMobileIsPc()) {
                        entity.setMobileUrl(form.getMobileUrl());
                    }

                    if (!form.getPrintIsPc()) {
                        entity.setPrintUrl(form.getPrintUrl());
                    }

                    entity.setPcUrl(form.getPcUrl());
                }

                if (null != form.getSortKey()) {
                    entity.setSortKey(form.getSortKey());
                }

                if (StringUtils.isNotEmpty(form.getName())) {
                    entity.setName(form.getName());
                }

                if (StringUtils.isNotEmpty(form.getName_i18n())) {
                    entity.setName_i18n(form.getName_i18n());
                }

                if (StringUtils.isNotEmpty(form.getIcon())) {
                    entity.setIcon(form.getIcon());
                }

                if (null != form.getMobileIsPc()) {
                    entity.setMobileIsPc(form.getMobileIsPc());
                }

                if (null != form.getPrintIsPc()) {
                    entity.setPrintIsPc(form.getPrintIsPc());
                }

                if (null != form.getPublished()) {
                    entity.setPublished(form.getPublished());
                }

                if (StringUtils.isNotEmpty(form.getPublishedViewJson())) {
                    entity.setPublishedViewJson(form.getPublishedViewJson());
                }

                if (StringUtils.isNotEmpty(form.getPublishedAttributesJson())) {
                    entity.setPublishedAttributesJson(form.getPublishedAttributesJson());
                }

                if (StringUtils.isNotEmpty(form.getDraftViewJson())) {
                    entity.setDraftViewJson(form.getDraftViewJson());
                }

                if (StringUtils.isNotEmpty(draftJson)) {
                    entity.setDraftAttributesJson(draftJson);
                }

                if (StringUtils.isNotEmpty(form.getModifiedBy())) {
                    entity.setModifiedBy(form.getModifiedBy());
                }

                if (StringUtils.isNotEmpty(form.getCreatedBy())) {
                    entity.setCreatedBy(form.getCreatedBy());
                }

                entity.setModifiedTime(new Date());
                if (null != form.getExternalLinkAble()) {
                    entity.setExternalLinkAble(form.getExternalLinkAble());
                }

                if (StringUtils.isNotEmpty(form.getShortCode())) {
                    entity.setShortCode(form.getShortCode());
                }

                if (StringUtils.isNotEmpty(form.getDraftActionsJson())) {
                    entity.setDraftActionsJson(form.getDraftActionsJson());
                }

                if (StringUtils.isNotEmpty(form.getDraftHtmlJson())) {
                    entity.setDraftHtmlJson(form.getDraftHtmlJson());
                }

                if (StringUtils.isNotEmpty(form.getPublishedHtmlJson())) {
                    entity.setPublishedHtmlJson(form.getPublishedHtmlJson());
                }

                if (StringUtils.isNotEmpty(form.getPublishedActionsJson())) {
                    entity.setPublishedActionsJson(form.getPublishedActionsJson());
                }

                if (StringUtils.isNotEmpty(form.getQrCodeAble())) {
                    entity.setQrCodeAble(form.getQrCodeAble());
                }

                if (StringUtils.isNotEmpty(form.getPrintTemplateJson())) {
                    entity.setPrintTemplateJson(form.getPrintTemplateJson());
                }

                if (StringUtils.isNotEmpty(form.getPdfAble())) {
                    entity.setPdfAble(form.getPdfAble());
                }

                if (StringUtils.isNotEmpty(form.getTempAuthSchemaCodes())) {
                    entity.setTempAuthSchemaCodes(form.getTempAuthSchemaCodes());
                }

                if (StringUtils.isNotEmpty(form.getBorderMode())) {
                    entity.setBorderMode(form.getBorderMode());
                }

                if (StringUtils.isNotEmpty(form.getLayoutType())) {
                    entity.setLayoutType(form.getLayoutType());
                }

                if (!Objects.isNull(form.getFormComment())) {
                    entity.setFormComment(form.getFormComment());
                }

                if (StringUtils.isNotEmpty(form.getPrintJson())) {
                    entity.setPrintJson(form.getPrintJson());
                }

                if (!Objects.isNull(form.getFormTrack())) {
                    entity.setFormTrack(form.getFormTrack());
                }

                if (StringUtils.isNotEmpty(form.getTrackDataCodes())) {
                    entity.setTrackDataCodes(form.getTrackDataCodes());
                }

                if (StringUtils.isNotEmpty(form.getFormSystemVersion())) {
                    entity.setFormSystemVersion(form.getFormSystemVersion());
                }

                if (StringUtils.isNotEmpty(form.getDraftSchemaOptionsJson())) {
                    entity.setDraftSchemaOptionsJson(form.getDraftSchemaOptionsJson());
                }

                entity.setExistDraft(form.getExistDraft());
                BizForm saved = (BizForm)super.update(entity);
                return saved;
            }
        }
    }

    public void delete(BizForm bizForm) {
        super.delete(bizForm);
    }

    private void validateProperty(String draftJson, String schemaCode, Set<String> deleteList) {
        Map<String, Object> map = (Map)JSON.parseObject(draftJson, Map.class);
        if (null != map && map.size() > 0) {
            Iterator var5 = map.keySet().iterator();

            while(true) {
                while(true) {
                    String code;
                    int type;
                    do {
                        do {
                            do {
                                do {
                                    do {
                                        do {
                                            do {
                                                if (!var5.hasNext()) {
                                                    return;
                                                }

                                                code = (String)var5.next();
                                                type = ((JSONObject)map.get(code)).getIntValue("type");
                                            } while(202 == type);
                                        } while(200 == type);
                                    } while(203 == type);
                                } while(90 == type);
                            } while(400 == type);
                        } while(500 == type);
                     } while(600 == type); //产品二开内容增加一个600类型

                    BizProperty property = this.bizPropertyService.get(schemaCode, code);
                    if (null == property) {
                        deleteList.add(code);
                    } else if (BizPropertyType.CHILD_TABLE.equals(property.getPropertyType())) {
                        JSONArray columns = ((JSONObject)map.get(code)).getJSONArray("columns");
                        if (!CollectionUtils.isEmpty(columns)) {
                            List<String> subList = new ArrayList();
                            Iterator iterator = columns.iterator();

                            while(iterator.hasNext()) {
                                JSONObject jsonObject = (JSONObject)iterator.next();
                                String subCode = jsonObject.getString("key");
                                BizProperty entity = this.bizPropertyService.get(code, subCode);
                                if (null == entity) {
                                    subList.add(code + "." + subCode);
                                }
                            }

                            if (columns.size() == subList.size()) {
                                deleteList.add(code);
                            } else {
                                deleteList.addAll(subList);
                            }
                        }
                    }
                }
            }
        }
    }

    public Boolean updateSortKey(String sheetCode, int sortKey, String schemaCode) {
        BizForm entity = this.getBySchemaCodeAndFormCode(schemaCode, sheetCode);
        if (entity == null) {
            log.debug("需要拖动的节点不存在： {}", sheetCode);
            return false;
        } else {
            List<BizForm> targetList = this.getListBySchemaCode(schemaCode);
            targetList = (List)targetList.stream().sorted(Comparator.comparingInt(BizForm::getSortKey)).collect(Collectors.toList());
            List<BizForm> bizFormInfo = new ArrayList();
            int startSortKey = entity.getSortKey();
            sortKey = targetList.size() < sortKey ? targetList.size() : sortKey;
            sortKey = sortKey < 1 ? 1 : sortKey;
            int endSortKey = ((BizForm)targetList.get(sortKey - 1)).getSortKey();
            Iterator var9;
            BizForm bizForm;
            if (startSortKey < endSortKey) {
                var9 = targetList.iterator();

                while(var9.hasNext()) {
                    bizForm = (BizForm)var9.next();
                    if (bizForm.getSortKey() > startSortKey && bizForm.getSortKey() <= endSortKey) {
                        bizForm.setSortKey(bizForm.getSortKey() - 1);
                        bizFormInfo.add(bizForm);
                    }
                }
            }

            if (startSortKey > endSortKey) {
                var9 = targetList.iterator();

                while(var9.hasNext()) {
                    bizForm = (BizForm)var9.next();
                    if (bizForm.getSortKey() >= endSortKey && bizForm.getSortKey() < startSortKey) {
                        bizForm.setSortKey(bizForm.getSortKey() + 1);
                        bizFormInfo.add(bizForm);
                    }
                }
            }

            entity.setSortKey(endSortKey);
            bizFormInfo.add(entity);
            if (CollectionUtils.isNotEmpty(bizFormInfo)) {
                bizFormInfo.stream().forEach((bizFormx) -> {
                    this.update(bizFormx);
                });
            }

            return true;
        }
    }

    public void verifyControlProperty(BizObjectModel bizObjectModel) {
        String schemaCode = bizObjectModel.getSchemaCode();
        String sheetCode = bizObjectModel.getFormCode();
        String bizId = bizObjectModel.getId();
        Map<String, Object> mapData = bizObjectModel.getData();
        String sequenceStatus = bizObjectModel.getSequenceStatus();
        if (SequenceStatus.PROCESSING.toString().equals(sequenceStatus) || SequenceStatus.COMPLETED.toString().equals(sequenceStatus) || SequenceStatus.DRAFT.toString().equals(sequenceStatus)) {
            BizForm bizForm = this.getBySchemaCodeAndFormCode(schemaCode, sheetCode);
            String str = bizForm.getPublishedAttributesJson();
            if (StringUtils.isNotEmpty(str)) {
                JSONObject jsonObject = JSON.parseObject(str);
                if (!ObjectUtils.isEmpty(jsonObject)) {
                    this.checkControl(bizObjectModel);
                }
            }

        }
    }

    private void checkControl(BizObjectModel bizObjectModel) {
        Map<String, Object> mapData = bizObjectModel.getData();
        if (!ObjectUtils.isEmpty(mapData)) {
            String schemaCode = bizObjectModel.getSchemaCode();
            String sheetCode = bizObjectModel.getFormCode();
            BizForm bizForm = this.getBySchemaCodeAndFormCode(schemaCode, sheetCode);
            if (bizForm != null) {
                List<BizDataRule> bizDataRules = this.getRepeatDataRule(schemaCode);
                String str = bizForm.getPublishedAttributesJson();
                if (!StringUtils.isBlank(str)) {
                    JSONObject jsonObject = JSON.parseObject(str);
                    if (!ObjectUtils.isEmpty(jsonObject)) {
                        Map<String, Object> parentCondition = new HashMap();
                        List<Map<String, Map<String, Object>>> childConditionList = new ArrayList();
                        Iterator var11 = mapData.entrySet().iterator();

                        while(true) {
                            while(true) {
                                Object value;
                                BizProperty bizProperty;
                                do {
                                    if (!var11.hasNext()) {
                                        log.info("parentCondition : {}", JSON.toJSONString(parentCondition, new SerializerFeature[]{SerializerFeature.WriteMapNullValue}));
                                        log.info("childConditionList : {}", JSON.toJSONString(childConditionList, new SerializerFeature[]{SerializerFeature.WriteMapNullValue}));
                                        this.checkParentControl(schemaCode, bizObjectModel.getId(), parentCondition, jsonObject.values());
                                        this.checkChildControl(mapData, childConditionList, jsonObject.values());
                                        return;
                                    }

                                    Entry<String, Object> entry = (Entry)var11.next();
                                    String key = (String)entry.getKey();
                                    value = entry.getValue();
                                    bizProperty = this.bizPropertyService.get(schemaCode, key);
                                } while(bizProperty == null);

                                if (BizPropertyType.SHORT_TEXT.equals(bizProperty.getPropertyType())) {
                                    Map<String, Object> params = this.getRepeatParamsByBizDataRule(bizProperty, value, bizDataRules);
                                    if (!ObjectUtils.isEmpty(params)) {
                                        parentCondition.putAll(params);
                                    }
                                } else if (BizPropertyType.CHILD_TABLE.equals(bizProperty.getPropertyType()) && value != null) {
                                    JSONArray childs = JSON.parseArray(JSON.toJSONString(value, new SerializerFeature[]{SerializerFeature.WriteMapNullValue}));

                                    for(int i = 0; i < childs.size(); ++i) {
                                        JSONObject childJson = childs.getJSONObject(i);
                                        if (!ObjectUtils.isEmpty(childJson)) {
                                            Map<String, Object> childParams = new TreeMap();
                                            Iterator var20 = childJson.entrySet().iterator();

                                            while(var20.hasNext()) {
                                                Entry<String, Object> child = (Entry)var20.next();
                                                BizProperty bp = this.bizPropertyService.get(bizProperty.getCode(), (String)child.getKey());
                                                if (bp != null) {
                                                    Map<String, Object> params = this.getRepeatParamsByBizDataRule(bp, child.getValue(), bizDataRules);
                                                    if (!ObjectUtils.isEmpty(params)) {
                                                        childParams.putAll(params);
                                                    }
                                                }
                                            }

                                            if (!ObjectUtils.isEmpty(childParams)) {
                                                Map<String, Map<String, Object>> childCondition = new HashMap();
                                                childCondition.put(bizProperty.getCode(), childParams);
                                                childConditionList.add(childCondition);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private List<BizDataRule> getRepeatDataRule(String schemaCode) {
        List<String> schemaCodes = this.getSchemaCodes(schemaCode);
        List<BizDataRule> bizDataRules = Lists.newArrayList();
        Iterator var4 = schemaCodes.iterator();

        while(var4.hasNext()) {
            String code = (String)var4.next();
            List<BizDataRule> subBizDataRule = this.bizDataRuleService.getListBySchemaCodeAndDataRuleType(code, DataRuleType.CHECK_RULE);
            if (!CollectionUtils.isEmpty(subBizDataRule)) {
                bizDataRules.addAll(subBizDataRule);
            }
        }

         bizDataRules = (List)bizDataRules.stream().filter((bizDataRule) -> {
            return bizDataRule.getCheckType() == 5;
        }).collect(Collectors.toList());
        return bizDataRules;
    }

    private List<String> getSchemaCodes(String schemaCode) {
        List<String> schemaCodes = Lists.newArrayList();
        schemaCodes.add(schemaCode);
        List<BizProperty> bizProperties = this.bizPropertyService.getListBySchemaCode(schemaCode, (Boolean)null);
        List<String> subSchemaCodes = (List)bizProperties.stream().filter((bizProperty) -> {
            return bizProperty.getPropertyType() == BizPropertyType.CHILD_TABLE;
        }).map(BizProperty::getCode).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(subSchemaCodes)) {
            return schemaCodes;
        } else {
            schemaCodes.addAll(subSchemaCodes);
            return schemaCodes;
        }
    }

    private boolean isAllNullOrEmptyValue(Map<String, Object> map) {
        if (ObjectUtils.isEmpty(map)) {
            return true;
        } else {
            Iterator var2 = map.values().iterator();

            Object value;
            do {
                if (!var2.hasNext()) {
                    return true;
                }

                value = var2.next();
            } while(ObjectUtils.isEmpty(value));

            return false;
        }
    }

    private void checkParentControl(String schemaCode, String bizId, Map<String, Object> params, Collection<Object> values) {
        if (!ObjectUtils.isEmpty(params) && !this.isAllNullOrEmptyValue(params)) {
            BizObjectQueryObject bizObjectQueryObject = this.getBizObjectQueryObject(schemaCode, bizId, params);
            List<Map<String, Object>> list = this.getQueryResult(bizObjectQueryObject, "查询列表");
            if (!CollectionUtils.isEmpty(list)) {
                StringBuffer errMsg = new StringBuffer();
                Iterator var8 = params.entrySet().iterator();

                while(var8.hasNext()) {
                    Entry<String, Object> entry = (Entry)var8.next();
                    JSONObject formMap = this.getFormMap((String)entry.getKey(), values);
                    String text = this.getFormName(formMap);
                    if (!ObjectUtils.isEmpty(text)) {
                        errMsg.append(text).append("、");
                    }
                }

                if (!ObjectUtils.isEmpty(errMsg)) {
                    errMsg.setLength(errMsg.length() - 1);
                    errMsg.append("不能重复");
                    throw new ServiceException(800150006L, errMsg.toString());
                }
            }
        }
    }

    private void checkChildControl(Map<String, Object> formData, List<Map<String, Map<String, Object>>> childConditionList, Collection<Object> values) {
        StringBuffer errMsg = new StringBuffer();
        Set<String> msgSet = new HashSet();
        Iterator var6 = childConditionList.iterator();

        while(var6.hasNext()) {
            Map<String, Map<String, Object>> childCondition = (Map)var6.next();
            Iterator var8 = childCondition.entrySet().iterator();

            while(var8.hasNext()) {
                Entry<String, Map<String, Object>> childParam = (Entry)var8.next();
                String key = (String)childParam.getKey();
                Map<String, Object> params = (Map)childParam.getValue();
                if (!this.isAllNullOrEmptyValue(params)) {
                    JSONArray data = JSON.parseArray(JSON.toJSONString(formData.get(key), new SerializerFeature[]{SerializerFeature.WriteMapNullValue}));
                    if (this.checkChildData(params, data)) {
                        JSONObject formMap = this.getFormMap(key, values);
                        String text = this.getFormName(formMap);
                        if (!ObjectUtils.isEmpty(text)) {
                            String childTextNames = this.getChildTextNames(text, params, values);
                            if (!msgSet.contains(childTextNames)) {
                                msgSet.add(childTextNames);
                                errMsg.append(childTextNames);
                            }
                        }
                    }
                }
            }
        }

        if (!ObjectUtils.isEmpty(errMsg)) {
            errMsg.setLength(errMsg.length() - 1);
            errMsg.append("不能重复");
            throw new ServiceException(800150006L, errMsg.toString());
        }
    }

    private String getChildTextNames(String parentName, Map<String, Object> params, Collection<Object> values) {
        StringBuffer names = new StringBuffer();
        Iterator var5 = params.entrySet().iterator();

        while(var5.hasNext()) {
            Entry<String, Object> param = (Entry)var5.next();
            JSONObject formMap = this.getFormMap((String)param.getKey(), values);
            String text = this.getFormName(formMap);
            if (!ObjectUtils.isEmpty(text)) {
                names.append(parentName).append("-").append(text).append("、");
            }
        }

        return names.toString();
    }

    private boolean checkChildData(Map<String, Object> params, JSONArray arrayData) {
        int count = 0;

        for(Iterator var4 = params.keySet().iterator(); var4.hasNext(); count = 0) {
            String key = (String)var4.next();
            Object value = params.get(key);

            for(int i = 0; i < arrayData.size(); ++i) {
                TreeMap<String, Object> data = new TreeMap(arrayData.getJSONObject(i));
                if (Objects.nonNull(value) && value.equals(data.get(key))) {
                    ++count;
                }
            }

            if (count > 1) {
                return true;
            }
        }

        return false;
    }

    private String concatValue(Map<String, Object> params, Map<String, Object> map) {
        StringBuffer concatValue = new StringBuffer();

        Object value;
        for(Iterator var4 = params.keySet().iterator(); var4.hasNext(); concatValue.append(value).append("#")) {
            String key = (String)var4.next();
            value = map.get(key);
            if (ObjectUtils.isEmpty(value)) {
                value = "";
            }
        }

        return concatValue.toString();
    }

    private Map<String, Object> getRepeatParamsByBizDataRule(BizProperty bizProperty, Object value, List<BizDataRule> bizDataRules) {
        Map<String, Object> params = new TreeMap();
        boolean exist = bizDataRules.stream().anyMatch((bizDataRule) -> {
            return StringUtils.equals(bizDataRule.getSchemaCode(), bizProperty.getSchemaCode()) && StringUtils.equals(bizDataRule.getPropertyCode(), bizProperty.getCode());
        });
        if (exist) {
            params.put(bizProperty.getCode(), value);
        }

        return params;
    }

    private Map<String, Object> getRepeatParams(BizProperty bizProperty, Object value, JSONObject jsonObject) {
        Map<String, Object> params = new TreeMap();
        if (BizPropertyType.SHORT_TEXT.equals(bizProperty.getPropertyType())) {
            if (bizProperty.getRepeated()) {
                params.put(bizProperty.getCode(), value);
                return params;
            }

            JSONObject formMap = this.getFormMap(bizProperty.getCode(), jsonObject.values());
            if (this.getFormNoRepeat(formMap)) {
                params.put(bizProperty.getCode(), value);
            }
        }

        return params;
    }

    private Boolean getFormNoRepeat(JSONObject formMap) {
        if (formMap == null) {
            return false;
        } else {
            JSONObject options = formMap.getJSONObject("options");
            return options == null ? false : Boolean.TRUE.equals(options.getBoolean("noRepeat"));
        }
    }

    private String getFormName(JSONObject formMap) {
        if (formMap == null) {
            return null;
        } else {
            JSONObject options = formMap.getJSONObject("options");
            return options == null ? null : options.getString("name");
        }
    }

    private JSONObject getFormMap(String schemaCode, Collection<Object> values) {
        Iterator var3 = values.iterator();

        while(var3.hasNext()) {
            Object value = var3.next();
            if (!ObjectUtils.isEmpty(value)) {
                JSONObject jsonObject = JSONObject.parseObject(value.toString());
                String key = jsonObject.getString("key");
                if (schemaCode.equals(key)) {
                    return jsonObject;
                }

                Integer type = jsonObject.getInteger("type");
                if (type != null) {
                    JSONArray panels;
                    JSONObject object;
                    if (type == 201) {
                        panels = jsonObject.getJSONArray("columns");
                        object = this.getFormMap(schemaCode, panels);
                        if (object != null) {
                            return object;
                        }
                    }

                    if (type == 500) {
                        panels = jsonObject.getJSONArray("panels");
                        object = this.getFormMap(schemaCode, panels);
                        if (object != null) {
                            return object;
                        }
                    }

                    if (type == 501) {
                        JSONObject controls = jsonObject.getJSONObject("controls");
                        if (!ObjectUtils.isEmpty(controls)) {
                            object = this.getFormMap(schemaCode, controls.values());
                            if (object != null) {
                                return object;
                            }
                        }
                    }
                }
            }
        }

        return null;
    }

    public BizForm getTempAuthSchemaCodesBySheetId(String id) {
        List<BizForm> tempAuthSchemaCodesAndSchemaCodeById = this.bizFormRepository.getTempAuthSchemaCodesAndSchemaCodeById(id);
        return CollectionUtils.isEmpty(tempAuthSchemaCodesAndSchemaCodeById) ? null : (BizForm)tempAuthSchemaCodesAndSchemaCodeById.get(0);
    }

    private BizObjectQueryObject getBizObjectQueryObject(String targetSchemaCode, String bizId, Map<String, Object> params) {
        final FilterExpression filterExpression = this.createConditionFilterExpression(bizId, params);
        return new BizObjectQueryObject() {
            public FilterExpression getFilterExpression() {
                return filterExpression;
            }

            public String getSchemaCode() {
                return targetSchemaCode;
            }

            public List<String> getDisplayFields() {
                List<String> list = new ArrayList();
                list.add("id");
                return list;
            }
        };
    }

    private FilterExpression createConditionFilterExpression(String bizId, Map<String, Object> params) {
        List<FilterExpression> filters = new LinkedList();
        filters.add(Q.or(Q.it("sequenceStatus", Op.Eq, "PROCESSING"), Q.it("sequenceStatus", Op.Eq, "COMPLETED"), new FilterExpression[0]));
        filters.add(Q.it("id", Op.NotEq, bizId));
        List<FilterExpression> itemFilters = Lists.newArrayList();
        Iterator var5 = params.entrySet().iterator();

        while(var5.hasNext()) {
            Entry<String, Object> entry = (Entry)var5.next();
            String key = (String)entry.getKey();
            Object value = entry.getValue();
            if (ObjectUtils.isEmpty(value)) {
                itemFilters.add(Q.or(Q.it(key, Op.Eq, ""), Q.it(key, Op.Eq, (Object)null), new FilterExpression[0]));
            } else {
                itemFilters.add(Q.it(key, Op.Eq, value));
            }
        }

        if (itemFilters.size() == 1) {
            filters.add(itemFilters.get(0));
        } else if (itemFilters.size() >= 2) {
            filters.add(Q.or(itemFilters));
        }

        return Q.and(filters);
    }

    public List<Map<String, Object>> getQueryResult(BizObjectQueryObject wrapped, String result) {
        List<BizProperty> bizProperties = this.bizPropertyService.getListBySchemaCode(wrapped.getSchemaCode(), true);
        List<Map<String, Object>> list = this.db.dml().find(wrapped, bizProperties);
        log.info(result + "查询列表结果 resultList:{}", JSON.toJSONString(list));
        return list;
    }

    public Map<String, BizForm> findBySchemaCodeIn(List<String> schemaCodes) {
        List<BizForm> bizForms = this.bizFormRepository.findBySchemaCodeInAndFormType(schemaCodes, BizFormType.DEFAULT_SHEET);
        return CollectionUtils.isEmpty(bizForms) ? Collections.emptyMap() : (Map)bizForms.stream().collect(Collectors.groupingBy(BizForm::getSchemaCode, Collectors.collectingAndThen(Collectors.reducing((c1, c2) -> {
            return c1.getSortKey() < c2.getSortKey() ? c1 : c2;
        }), Optional::get)));
    }

    public void removePropertyFromJson(BizProperty bizProperty) {
        String schemaCode = bizProperty.getSchemaCode();
        BizProperty mainProperty = (BizProperty)this.bizPropertyService.getListByPropertyCode(schemaCode).stream().filter((p) -> {
            return Objects.equals(BizPropertyType.CHILD_TABLE, p.getPropertyType());
        }).findAny().orElse(null);
        String childSchemaCode = null;
        if (mainProperty != null) {
            childSchemaCode = bizProperty.getSchemaCode();
            schemaCode = mainProperty.getSchemaCode();
        }

        List<BizForm> bizForms = this.bizFormRepository.findBySchemaCodeAndFormType(schemaCode, BizFormType.DEFAULT_SHEET);
        Iterator var6 = bizForms.iterator();

        while(var6.hasNext()) {
            BizForm it = (BizForm)var6.next();
            boolean needUpdate = false;
            cn.hutool.json.JSONObject publishAttributesJson;
            cn.hutool.json.JSONObject publishJson;
            if (JSONUtil.isJson(it.getDraftAttributesJson())) {
                publishAttributesJson = JSONUtil.parseObj(it.getDraftAttributesJson());
                if (!publishAttributesJson.isEmpty()) {
                    publishJson = this.bizFormJsonResolveService.doRemovePropertyFromJson(publishAttributesJson, bizProperty.getCode(), childSchemaCode);
                    if (publishJson != null) {
                        it.setDraftAttributesJson(publishJson.toString());
                        needUpdate = true;
                        log.debug("[delete property] remove property from draft json, code={}", bizProperty.getCode());
                    }
                }
            }

            if (bizProperty.getPublished() && JSONUtil.isJson(it.getPublishedAttributesJson())) {
                publishAttributesJson = JSONUtil.parseObj(it.getPublishedAttributesJson());
                if (!publishAttributesJson.isEmpty()) {
                    publishJson = this.bizFormJsonResolveService.doRemovePropertyFromJson(publishAttributesJson, bizProperty.getCode(), childSchemaCode);
                    if (publishJson != null) {
                        it.setPublishedAttributesJson(publishJson.toString());
                        needUpdate = true;
                        log.debug("[delete property] remove property from publish json, code={}", bizProperty.getCode());
                    }
                }
            }

            if (needUpdate) {
                this.update(it);
            }
        }

    }

    public List<BizFormModel> getFormByPropertyExist(String schemaCode, String propertyCode, String childSchemaCode) {
        List<BizForm> bizForms = this.bizFormRepository.findBySchemaCodeAndFormType(schemaCode, BizFormType.DEFAULT_SHEET);
        if (CollectionUtils.isEmpty(bizForms)) {
            return null;
        } else {
            bizForms = (List)bizForms.stream().filter((it) -> {
                return it.getPublishedAttributesJson() != null && this.bizFormJsonResolveService.judgePropertyUsedByForm(JSONUtil.parseObj(it.getPublishedAttributesJson()), propertyCode, childSchemaCode);
            }).collect(Collectors.toList());
            return ModelUtil.toModel(bizForms, BizFormModel.class);
        }
    }

    public int count(String schemaCode, BizFormType formType) {
        return this.bizFormRepository.countBySchemaCodeAndFormType(schemaCode, formType);
    }

    protected void initCacheConfig() {
        Map<String, Object> externInfo = Maps.newHashMap();
        externInfo.put("tableName", "h_biz_sheet");
        this.setCacheConfig(new CacheConfig(externInfo, "表单元数据表"));
    }
}
